<template>
    <div v-loading="loading">
        <div v-if="!url" :element-loading-text="loadingProgressText" element-loading-spinner="el-icon-loading">
            <el-upload class="upload-demo" :show-file-list="false" :drag="true" :auto-upload="false"
                :on-change="handleChange" :before-upload="beforeUpload" action="#" :accept="accept">
                <i class="el-icon-upload"></i>

            </el-upload>
        </div>
        <div v-else>
            <div class="preview-container" @mouseover="mouseover" @mouseleave="mouseleave">
                <a class="el-upload-list__item-name">
                    <i class="el-icon-document custom-originFileName">{{ originFileName }}</i>
                    <i class="custom-delete-button el-icon-delete" @click="deleteFiles"></i>
                </a>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        url: { type: String, default: "" },
        prefix: { type: String, default: "topic/material" },
        accept: {
            type: String,
            default: "*" // 添加了文件和文档格式
        },
        showToast: { type: Boolean, default: false },
    },
    data() {
        return {
            loading: false,
            src: this.url,
            deleteButtonHover: false,
            loadingProgressText: "",
            originFileName: ""
        };
    },
    mounted() {
        if (this.url) {
            this.src = this.url;
        }
    },
    methods: {

        mouseover() {
            this.deleteButtonHover = true;
        },

        mouseleave() {
            this.deleteButtonHover = false;
        },

        handleChange(file) {
            if (file.status === "ready") {
                this.uploadFile(file.raw);
            }
        },
        beforeUpload(file) {
            const acceptedTypes = this.accept.toLowerCase().split(',').map(type => type.trim());
            const extension = file.name.slice((file.name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
            const isValidType = acceptedTypes.includes('.' + extension);

            if (!isValidType) {
                this.$message.error(`只能上传以下类型的文件：${this.accept}`);
            }

            return isValidType;
        },

        async uploadFile(file) {
            this.originFileName = file.name;
            const startTime = Date.now();
            try {
                this.loading = true;
                const res = await this.$fetch.cosUplod(file, `/assets/${this.prefix}`, {
                    onProgress: (percent, speed, total) => {
                        const current = (total * (percent * 0.01)).toFixed(2);
                        this.loadingProgressText = `${current}Mb / ${total}Mb ,  速度：${speed}Mb/s, 进度：${percent}%;`;
                    },
                    onFileFinish: () => {
                        this.loadingProgressText = "";
                        this.loading = false;

                    }
                });
                if (res) {
                    this.showToast && this.$message.success("文件上传成功！");
                    this.update(res);
                } else {
                    throw new Error("文件上传失败");
                }
            } catch (error) {
                console.error("上传错误:", error);
                this.$message.error("文件上传出错，请重试！");
            } finally {
                const endTime = Date.now();
                console.log(`上传完成，耗时${(endTime - startTime) / 1000}秒`);
                this.loading = false;
            }
        },

        async deleteFiles() {
            const { code } = await this.$fetch.post("/api/cos-delete", {
                url: this.src,
            });
            if (code === 0) {
                this.update("")
            }
        },

        update(src) {
            this.src = src;
            this.$emit("update:url", src);
        },
    },
}
</script>


<style lang="less" scoped>
.custom-originFileName {
    font-size: 26px;
    display: inline-flex;
    align-items: center;
    justify-content: center;

}

.custom-delete-button {
    margin-left: 40px;
    font-size: 26px;
    display: inline-flex;
    align-items: center;
    justify-content: center;

}
</style>